import dynamic from 'next/dynamic'
import Layout from '@c/layout'
import HFilmList from '@c/h-film-list'
import FilterTab from '@c/filter-tab'
import { useRouter } from 'next/router'
import styles from './index.module.scss'
import { useEffect, useState, useRef } from 'react'
import cm from 'classnames'
import { getFilterCondition, getFilterData } from '@/api/filter'
import { FILM_OBJ, FILE_URL, COUNTRY_URL, AREA_GET, AREA_MAP_EN_FUNC } from '@/constant'
import { getYearFilterData } from '@/utils/date'
import { useSolveStickyPower } from '@/utils/hooks'
import { isElementInViewport } from '@/utils/utils'
import Link from 'next/link'
import throttle from 'lodash-es/throttle'
import { userInfo } from '@/store'
import { useRecoilValue } from 'recoil'

const Null = dynamic(() => import('@c/null'))
const Loading = dynamic(() => import('@c/loading'))

// 时间段
const times = getYearFilterData()

// 描述语言组装
const getLabel = (label, list) => {
  let str = ''
  try {
    str = list.filter(item => item[1] === label)[0][0]
  } catch (error) {}
  return str
}
const descWordFunc = (params, filterCondition) => {
  const { tab, year, tag, area } = params
  let str = ''
  if (tab === 'drama') {
    if (year == tag && tag == area && area == 'all') return '电视剧库'
    str += year === 'all' ? '' : year + '年'
    str += tag === 'all' ? '' : getLabel(tag, filterCondition?.label || [])
    str += area === 'all' ? '电视剧' : AREA_GET(AREA_MAP_EN_FUNC(area, 2))
    return !str ? `${FILM_OBJ[params.tab]}库` : str
  } else {
    str += year === 'all' ? '' : year + '年'
    str += area === 'all' ? '' : AREA_MAP_EN_FUNC(area, 2)
    str += tag === 'all' ? '' : getLabel(tag, filterCondition?.label || [])
    str += year === 'all' && area === 'all' && tag === 'all' ? '' : FILM_OBJ[tab]
    return !str ? `${FILM_OBJ[tab]}库` : str
  }
}

// 页面标题与描述组装
const pageInfoFunc = (params, descWord) => {
  const { tab, year, tag, area } = params
  if (year === 'all' && tag === 'all' && area === 'all') {
    return {
      title: `最新${FILM_OBJ[tab]}推荐 - 星视界-华人影视大全`,
      desc: `星视界${FILM_OBJ[tab]}片库，为您推荐${new Date().getFullYear()}最好看的高清${
        FILM_OBJ[tab]
      }。立即访问网站，开始享受高质量的影视内容吧！`
    }
  }
  return {
    title: `${descWord}在线观看 - 星视界`,
    desc: `星视界为您推荐最精彩的${descWord}，立即访问，开始享受高质量影视内容吧！`
  }
}

const currYear = target => {
  let time = ''
  try {
    time = times.filter(item => item.id == target)[0]
  } catch (error) {}
  return time
}

// 跳转链接与参数组装
const assembleUrl = ({ tab, year, tag, area }, filterCondition, page, pageSize = 12) => {
  const chName = FILM_OBJ[tab]
  const url = `/${tab}/${year}/${tag}/${AREA_MAP_EN_FUNC(area)}`
  return {
    url,
    params: {
      country: area === 'all' ? undefined : AREA_MAP_EN_FUNC(area, 2),
      label: tag === 'all' ? undefined : getLabel(tag, filterCondition?.label || []),
      chName,
      startTime: year === 'all' ? undefined : currYear(year)?.startTime,
      endTime: year === 'all' ? undefined : currYear(year)?.endTime,
      pageSize,
      page
    }
  }
}

const generateUrl = ({ tab, year, tag, area }) => {
  return `/${tab}/${year}/${tag}/${AREA_MAP_EN_FUNC(area)}`
}

const Index = props => {
  const { filterCondition, params, total, initCard, descWord } = props
  const user = useRecoilValue(userInfo)
  const { tab, year, tag, area } = params
  const [label, setLabel] = useState(params.tag)
  const [country, setCountry] = useState(params.area)
  const [time, setTime] = useState(params.year)
  const router = useRouter()
  const [card, setCard] = useState(initCard)
  const [page, setPage] = useState(2) //初始page为2，是因为首次加载了32条，所以下次请求需要从3开始，page大于一百则不再处理了
  const [init, setInit] = useState(false)
  const [isEnd, setIsEnd] = useState(false)
  const ref = useRef(null)
  const refSearch = useRef(null)
  const [isLoading, setLoading] = useState(false)
  const [panelShow, setPanelShow] = useState({})
  // url变化归位
  useEffect(() => {
    setPage(2)
    setCard(initCard)
    setIsEnd(!initCard.length)
  }, [router.asPath, initCard])

  // 下滑加载更多函数
  const updateData = async () => {
    const filterParams = assembleUrl(params, filterCondition, page).params
    setLoading(true)
    const filterData = await getFilterData(filterParams)
    setCard([...card, ...(filterData.data?.list || [])])
    setIsEnd(!filterData.data?.list?.length)
    setLoading(false)
  }

  // page变化，加载数据
  useEffect(() => {
    if (!init || page === 2 || isEnd || page > 100) return
    updateData()
  }, [page])

  // 下滑监听
  const handleScroll = () => {
    if (isElementInViewport(ref.current)) {
      setPage(page => page + 1)
    }
  }
  useEffect(() => {
    setInit(true)
    const scrollListen = throttle(handleScroll, 500)
    const closePanel = () => setPanelShow({})
    window.addEventListener('scroll', scrollListen)
    window.addEventListener('click', closePanel)
    return () => {
      window.removeEventListener('scroll', scrollListen)
      window.removeEventListener('click', closePanel)
      sessionStorage.setItem('lastPage', true)
    }
  }, [])
  const filterArr = [
    {
      showPanel: panelShow?.label,
      name: '分类',
      value: [['all', 'all'], ...(filterCondition?.label || [])],
      getUrl: item => generateUrl({ tab, year, area, tag: item[1] }),
      isActive: item => item[1] === label,
      onClick: item => setLabel(item[1]),
      renderName: () => {
        const res = (filterCondition?.label || []).filter(item => item[1] === label)?.pop()
        if (res) {
          return res[0]
        }
        return '分类'
      },
      render: item => (item[0] === 'all' ? '全部' : item[0]),
      toggleShow: e => {
        e.stopPropagation()
        setPanelShow({ label: !panelShow?.label })
      }
    },
    {
      showPanel: panelShow.country,
      name: '地区',
      value: ['all', ...(filterCondition?.country || [])],
      getUrl: item => generateUrl({ tab, year, area: item, tag }),
      isActive: item => item === AREA_MAP_EN_FUNC(country, 2),
      onClick: item => setCountry(item),
      renderName: () => {
        const res = (filterCondition?.country || []).filter(item => item === AREA_MAP_EN_FUNC(country, 2))?.pop()
        if (res) {
          return res
        }
        return '地区'
      },
      render: item => (item === 'all' ? '全部' : item),
      toggleShow: e => {
        e.stopPropagation()
        setPanelShow({ country: !panelShow.country })
      }
    },
    {
      showPanel: panelShow.time,
      name: '上映年份',
      value: times,
      getUrl: item => generateUrl({ tab, year: item.id, area, tag }),
      isActive: item => item.id == time,
      onClick: item => setTime(item.id),
      renderName: () => {
        const res = times.filter(item => item.id == time)?.pop()
        if (!res || res.label == '全部') {
          return '上映年份'
        }
        return res.label
      },
      render: item => item?.label,
      toggleShow: e => {
        e.stopPropagation()
        setPanelShow({ time: !panelShow.time })
      }
    }
  ]

  // sitcy属性兼容
  useSolveStickyPower()

  // 搜索内容
  const search = () => {
    const value = refSearch.current.value
    if (!value) {
      refSearch.current.focus()
      return
    }
    router.push(`/search?word=${value}`)
  }

  return (
    <Layout className={cm(styles.filterContainer, styles.filterContainerPhone)}>
      <div className={cm(styles.filterBox, 'sticky')}>
        <FilterTab active={2} url={params.tab} />
        {filterArr.map((list, index) => {
          return (
            <div className={cm(styles.filter, list.showPanel ? styles.filterActive : '')} key={index}>
              <div className={styles.filterContent} onClick={list.toggleShow}>
                <span>{list.renderName()}</span>
                <img loading="lazy" src="/images/ar.png" alt="箭头" />
              </div>
              <div className={styles.filterPanel}>
                {list.value.map((item, index) => {
                  return (
                    <Link
                      replace
                      href={list.getUrl(item)}
                      key={index}
                      className={cm(styles.item, {
                        [styles.itemActive]: list.isActive(item)
                      })}
                      onClick={() => list.onClick(item)}
                    >
                      {list.render(item)}
                    </Link>
                  )
                })}
              </div>
            </div>
          )
        })}
      </div>
      <div className={cm(styles.query, 'sticky')}>
        <h1>{descWord}</h1>
        <p>共{total}部</p>
      </div>
      <div className={styles.allBody}>
        {!card.length ? (
          <Null />
        ) : (
          <HFilmList hideCollect={true} showTitle={false} data={{ cards: card }} source={'/' + tab} isSearchPage />
        )}
      </div>
      <div className={styles.loading} ref={ref}>
        {page > 100 ? (
          <div className={styles.ended}>
            <p className={styles.endText}>没找到想看的内容？</p>
            <div className={styles.search}>
              <input placeholder="试试搜索看吧" ref={refSearch} />
              <img src="/images/search.png" alt="" onClick={search} />
            </div>
          </div>
        ) : (
          <Loading isLoading={isLoading} />
        )}
      </div>
    </Layout>
  )
}
export default Index

export async function getServerSideProps({ params }) {
  const { tab, year, tag, area } = params
  // 一级路由判定
  if (!FILE_URL.includes(params.tab)) {
    return { notFound: true }
  }
  // 二级路由判定
  if (year != 'all' && !times.find(item => item.id == year)) {
    return { notFound: true }
  }

  const res1 = await getFilterCondition({ chName: FILM_OBJ[tab] }, {})
  const res1Data = res1?.data || {}

  // 三级路由判定
  try {
    const label = res1Data.label
    if (tag != 'all' && label.every(item => item[1] != tag)) {
      return { notFound: true }
    }
  } catch (error) {
    return { notFound: true }
  }

  // 四级路由判定

  try {
    if (area != 'all' && !COUNTRY_URL.includes(area)) {
      return { notFound: true }
    }
  } catch (error) {
    return { notFound: true }
  }
  const filterParams = assembleUrl(params, res1Data, 1, 24).params
  const res2 = await getFilterData(filterParams, {})
  const res2Data = res2?.data || {}
  const descWord = descWordFunc(params, res1Data)
  const pageInfo = pageInfoFunc(params, descWord)
  return {
    props: {
      params,
      filterCondition: res1Data,
      total: res2Data?.total || 0,
      initCard: res2Data?.list || [],
      descWord,
      layoutProps: {
        noSomeMetaInfo: false,
        url: '/' + tab,
        ...pageInfo
      }
    }
  }
}
